var trap = function(height) {
  const len = height.length;

  let ans = 0, left = 0, right = len - 1, leftMax = 0, rightMax = 0;

  while (left < right) {
    leftMax = Math.max(leftMax, height[left]);
    rightMax = Math.max(rightMax, height[right]);

    // 水只能接在较小的那一边 
    if (leftMax < rightMax) {
      ans += leftMax - height[left];
      left++;
    } else {
      ans += rightMax - height[right];
      right--;
    }
  }
  return ans;

};